import axios from 'axios'
import { ElMessage } from 'element-plus'
import useUserStore from '@/stores/user'
import router from '@/router/index'

const server = axios.create({
  baseURL: '/api',
  timeout: 5000,
})

server.interceptors.request.use((config) => {
  if (config.url == '/login') {
    return config
  }
  let user = useUserStore()

  config.headers.token = user.getUser.token
  return config
})

let errorList = {
  ERR_BAD_RESPONSE: '服务器重启中',
  ERR_BAD_REQUEST: '请求错误',
}

server.interceptors.response.use(
  function (response) {
    let { code, msg } = response.data
    if (code != 200) {
      ElMessage.error(msg)
      if (code === 401) {
        router.push('/login')
        return
      }
    }
    return response.data
  },
  function (error) {
    ElMessage.error(errorList[error.code])
    return
  },
)

export default server
